<?php

class UserSetting extends AppModel {

    var $name = 'UserSetting';
    
    var $belongsTo = array(
        'User' => array(
            'className'     => 'User',
            'foreignKey'    => 'id',
        )
    );
    
    public function get($user_id,$force = false) {
    	$cache_key = 'user_setting_'.$user_id;
    	$settings = Cache::read($cache_key);
    	if( $settings === false || $force ) {
	    	$data = $this->findById($user_id);
	    	if(!empty($data['UserSetting']['settings'])) {
	    		$settings = json_decode($data['UserSetting']['settings'],true);
	    	}
	    	else{
	    	    $settings = array();
	    	}
	    	Cache::write($cache_key, $settings);
    	}
    	return $settings;
    }

    public function setKeyVal($id, $key, $value) {

        $settings = $this->get($id,true);
        //数组相加已前面的为准
        $settings[$key] = $value;

        $data = array(
            'id'=>$id,
            'settings' => json_encode($settings)
        );
        $this->save($data);

        $cache_key = 'user_setting_'.$id;
        Cache::delete($cache_key);
    }
    
    public function write($id,array $settings) {
    	
    	$old_settings = $this->get($id,true);
        //数组相加已前面的为准
    	$settings = $settings + $old_settings;
    	
    	$data = array(
    		'id'=>$id,
    		'settings' => json_encode($settings)
    	);
    	$this->save($data);
    	
    	$cache_key = 'user_setting_'.$id;
    	Cache::delete($cache_key);
    }
   
}
?>